package cn.edu.pzhu.javaweb.service.imp;

import java.sql.Connection;
import java.sql.SQLException;

import cn.edu.pzhu.javaweb.dao.UserDao;
import cn.edu.pzhu.javaweb.dao.UserinfoDao;
import cn.edu.pzhu.javaweb.dao.imp.UserDaoImp;
import cn.edu.pzhu.javaweb.dao.imp.UserinfoDaoImp;
import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.pojo.Userinfo;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.util.DBUtil;

public class UserServiceImp implements UserService{

	private UserDao userdao = new UserDaoImp();
	private UserinfoDao userinfoDao = new UserinfoDaoImp();
	@Override
	public Result<String> regist(User user, Userinfo userinfo) {
		// TODO Auto-generated method stub
	    if (user == null || user.getUsername() == null || user.getPassword() == null
	            || user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
	            return Result.badRequest("数据异常！");
	        }
	        if (userinfo == null || userinfo.getUsername() == null || userinfo.getEmail() == null
	            || userinfo.getType() == null || userinfo.getType().isEmpty()) {
	            return Result.badRequest("数据异常！");
	        }
	        
	        // 检查用户是否已存在
	        User dbuser = userdao.selectById(user.getUsername());
	        if (dbuser != null) {
	            return Result.badRequest("用户已经被注册！");
	        }
	        
	        // 事务管理
	        Connection con = null;
	        try {
	            con = DBUtil.getConnection();
	            con.setAutoCommit(false); // 关闭自动提交
	            
	            int i = userdao.insert(user, con);
	            int j = userinfoDao.insert(userinfo, con);
	            
	            if (i > 0 && j > 0) {
	                con.commit();
	                return Result.success("注册成功！");
	            } else {
	                con.rollback();
	                return Result.error("注册失败！");
	            }
	        } catch (SQLException e) {
	            try {
	                if (con != null) {
	                    con.rollback();
	                }
	            } catch (SQLException ex) {
	                ex.printStackTrace();
	            }
	            e.printStackTrace();
	            return Result.error("系统异常，注册失败！");
	        } finally {
	            DBUtil.closeConnection(con);
	        }
	}

	@Override
	public Result<String> login(User user) {
		// TODO Auto-generated method stub
	    // 参数验证
	    if (user == null || user.getUsername() == null || user.getPassword() == null
	        || user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
	        return Result.badRequest("数据异常");
	    }
	    
	    // 查询用户
	    User dbuser = userdao.selectById(user.getUsername());
	    if (dbuser == null) {
	        return Result.notFound("用户不存在");
	    }
	    
	    // 检查账户状态
	    if (dbuser.getStatus() == 0) {
	        return Result.forbidden("账户已经被撤销！");
	    }
	    
	    // 添加账户注销状态检查
	    if (dbuser.getStatus() == 2) {
	        return Result.forbidden("账户已经被注销！");
	    }
	    
	    // 验证密码
	    if (!dbuser.getPassword().equals(user.getPassword())) {
	        return Result.unauthorized("密码错误");
	    }
	    
	    // 登录成功
	    return Result.success("登录成功");
	}

	@Override
	public Result<Userinfo> getPersonalInfo(String username) {
		if(username==null || username.isEmpty()) {
			return Result.badRequest("数据异常");
		}
		Userinfo userinfo = userinfoDao.selectById(username);
		return Result.success(userinfo);
	}

	@Override
	public Result<String> updatePersonalInfo(Userinfo userinfo) {
		if(userinfo==null || userinfo.getUsername()==null || userinfo.getEmail()==null
				|| userinfo.getType().isEmpty()) {
			return Result.badRequest("数据异常");
		}
		int n = userinfoDao.updateById(userinfo);
		if(n==1) {
			return Result.success();
	}
		return Result.badRequest("数据更新失败");
	}

	@Override
	public Result<String> updatePassword(User user) {
		if (user == null || user.getUsername() == null || user.getPassword() == null
		        || user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
		    return Result.badRequest("数据异常！");
		}
		
		// 先查询用户是否存在
		User dbuser = userdao.selectById(user.getUsername());
		if (dbuser == null) {
		    return Result.notFound("用户不存在！");
		}
		
		// 检查账户状态
		if (dbuser.getStatus() == 0 || dbuser.getStatus() == 2) {
		    return Result.forbidden("账户已被禁用或注销，无法修改密码！");
		}
		
		// 更新密码
		int n = userdao.updateById(user);
		if (n == 1) {
		    return Result.success("密码修改成功！");
		} else {
		    return Result.error("密码修改失败！");
		}
	}

	@Override
	public Result<String> destroyAccount(String username) {
		if (username == null || username.isEmpty()) {
		    return Result.badRequest("数据异常！");
		}
		
		// 先查询用户是否存在
		User dbuser = userdao.selectById(username);
		if (dbuser == null) {
		    return Result.notFound("用户不存在！");
		}
		
		// 检查账户状态
		if (dbuser.getStatus() == 0 || dbuser.getStatus() == 2) {
		    return Result.forbidden("账户已被禁用或注销！");
		}
		
		// 设置账户状态为注销（2表示注销）
		dbuser.setStatus(2);
		int n = userdao.updateById(dbuser);
		if (n == 1) {
		    return Result.success("账户注销成功！");
		} else {
		    return Result.error("账户注销失败！");
		}
	}

	@Override
	public boolean checkUsername(String username) {
		if (username==null || username.isEmpty()) {
			return false;
		}
		User dbUser =userdao.selectById(username);
		if (dbUser!=null) {
			return true;
		}else {
			return false;
		}
	}

}
